//表单验证
    $(function addJudge(){
        //成为焦点
        $('.name,.studio,.age,.address,.parent,.phone,.relation').on('focus',function(){
            $(this).siblings(".tip-error").hide();
        });
    
        //失去焦点
        $('.name').on('blur',function(){
    
            var current = $(event.target);
            var value = current.val();
    
            fromEvent(current,value,'name','必填','填写正确的姓名！','√');
    
        });
        $('.studio').on('blur',function(){
    
            var current = $(event.target);
            var value = current.val();
    
            fromEvent(current,value,'studio','必填','只能是数字！','√');
    
        });
    
        $('.relation').on('blur',function(){
    
            var current = $(event.target);
            var value = current.val();
    
            fromEvent(current,value,'relation','必填','填写正确关系！','√');
    
        });
    
    
        $('.age').on('blur',function(){
            var current = $(event.target);
            var value = current.val();
    
            fromEvent(current,value,'age','必填','请输入正确的年级！','√');
    
        });
    
        $('.address').on('blur',function(){
            var current = $(event.target);
            var value = current.val();
    
            fromEvent(current,value,'address','必填','错误','√');
    
        });
        $('.phone').on('blur',function(){
            var current = $(event.target);
            var value = current.val();
    
            fromEvent(current,value,'phone','必填','请输入正确的联系方式！','√');
    
        });
        $('.parent').on('blur',function(){
            var current = $(event.target);
            var value = current.val();
    
            fromEvent(current,value,'parent','必填','请输入正确的姓名！','√');
    
        });
    
        
    
        function fromEvent(current,value,name,text1,text2,past){
    
            if(value == ""){
                //非空验证
                current.siblings('.tip-error').text(text1).show();
            }else if(!checkFilter(name,value)){
                //正则验证
                current.siblings('.tip-error').text(text2).show();
    
            }else{
                //验证通过
                current.siblings(".tip-error").hide();
                current.siblings('.tip-error').text(past).show();
            }
        }
    
        function checkFilter(name,value){
    
            if(name == '') return true;
            var filter;
            switch(name){
                case 'name':
                    filter = /^[\u4E00-\u9FA5]{2,4}$/;
                    break;
                case 'parent':
                    filter = /^[\u4E00-\u9FA5]{2,4}$/;
                    break;
                case 'phone':
                    filter = /^1[34578]\d{9}$/;
                    break;
    
                case 'address':
                    filter = /^[\u4E00-\u9FA5]{2,10}$/;
                    break;
    
                case 'age':
                    filter =  /^[\u4E00-\u9FA5]{2,4}$/;
                    break;
                case 'studio':
                    filter = /^[0-9]{1,5}$/;
                    break;
                case 'relation':
                    filter = /^[\u4E00-\u9FA5]{2,4}$/;
                    break;
                
                
            }
    
            if(filter.test(value)){
                return true;
            }else{
                return false;
            }
        }
    });

// 日期的设置
// 年
var date=new Date().getFullYear();
for (let i=date-10;i<date; i++) {
    var txt=$("<option></option>").text(i);
    $(".Year").append(txt)
};
//月
for (let i = 1; i <= 12; i++) {
    var txt=$("<option></option>").text(i);
    $(".Month").append(txt)
};
//日
for (let i = 1; i <= 31; i++) {
    var txt=$("<option></option>").text(i);
    $(".Day").append(txt)
};
//区分每个月对应的天数
$(".Year").change(function () {
    $(this).siblings(".Month").html("<option>"+"</option>");
    $(this).siblings(".Day").html("<option>"+"</option>");
    for(i=1;i<=12;i++){
        var txt=$("<option></option>").text(i);
        $(this).siblings(".Month").append(txt)
    }
});
$(".Month").change(function () {
    var Yea = parseInt($($(this).siblings(".Year")).val());
    var Mon = parseInt($(this).val());
    if(Mon==1||Mon==3||Mon==5||Mon==7||Mon==8||Mon==10||Mon==12){
        $(this).siblings(".Day").html("<option>"+"</option>");
        for(i=1;i<=31;i++){
            var txt=$("<option></option>").text(i);
            $(this).siblings(".Day").append(txt)
        }
    }else if(Mon==4||Mon==6||Mon==9||Mon==11){
        $(this).siblings(".Day").html("<option>"+"</option>");
        for(i=1;i<=30;i++){
            var txt=$("<option></option>").text(i);
            $(this).siblings(".Day").append(txt)
        }
    }else if(Mon==2&&((Yea%4==0&&Yea%100!=0)||Yea%400==0)){
        $(this).siblings(".Day").html("<option>"+"</option>");
        for(i=1;i<=29;i++){
            var txt=$("<option></option>").text(i);
            $(this).siblings(".Day").append(txt)
        }
    }else if(Mon==2){
        $(this).siblings(".Day").html("<option>"+"</option>");
        for(i=1;i<=28;i++){
            var txt=$("<option></option>").text(i);
            $(this).siblings(".Day").append(txt)
        }
    }
});
//重新排序函数
function itemResort(page) {
    for (var i = 0; i < $('.table1').children().children().length; i++) {
        if (i >= 1) {
            $('.table1').children().children().eq(i).children().eq(0).text((page-1)*6+i);
        }
    }
};
var pd=true;
var operateItem = '';
//每页的最大数量
var itemMax = 6;
//当前页面
var nowPage = 1;
var firstItem = itemMax * (nowPage - 1);
var lastItem = itemMax * (nowPage);
var studentArr = JSON.parse(localStorage.getItem('studentJson'));
var Name;
function countNum(name){
	var num=0;
    $.each(getStaffArr,function(index,value){
		if(value.student==name){
			num++;
		}
	})
	return num;
};
$.each(studentArr, function(index, value) {
	if (index >= firstItem && index < lastItem) {
		createList($('.table1'), index, value);
	}
})
//创建分页
createPage();
function createPage() {
	var read = JSON.parse(localStorage.getItem('studentJson'));
	$('.pagination').append('<li><a href="javascript:;" id="leftPage"><span style="font-size: 14px;">&laquo;</span></a></li>');
	for (var i = 0; i < Math.ceil(read.length / itemMax); i++) {
			$('.pagination').append('<li><a href="javascript:;" class="pageNum" id="' + (i + 1) + '">' + (i + 1) + '</a></li>');
	}
	$('.pagination').append('<li><a href="javascript:;" id="rightPage"><span style="font-size: 14px;">&raquo;</span></a></li>');
};
function createList(obj, index, value) {
	$('tbody').append('<tr><td>' + (index + 1) +
    '</td><td>' + value.name + '</td><td>' + value.id + 
    '</td><td>' + value.class +
    '</td><td>' +value.age +'</td><td>' + value.sex + 
    '</td><td>' + value.birth +'</td><td>' + value.address + 
    '</td><td>' + value.parent +'</td><td>' + value.phone + 
    '</td><td>' + value.relation +'</td><td>' + 
		'<button type="button" class="btn btn-primary btn-sm edit" id="edit" data-toggle="modal" data-target="#studentEdit">编辑</button>' +
		'<button type="button" class="btn btn-warning btn-sm delete" id="delete" data-toggle="modal" data-target="#studentDelete">删除</button>' 
	);
};
//为分页添加事件
$('.pagination').on('click', 'a', function() {
	if ($(this).attr('id') == 'leftPage') {
		if ($('.pageNum[id=' + nowPage + ']').parent().prev().children().eq(0).attr('id') != 'leftPage') {
			$(this).parent().removeClass('disabled');
			nowPage -= 1;
			$("tr:not('.headline')").remove();
			firstItem = itemMax * (nowPage - 1);
			lastItem = itemMax * (nowPage);
			var read = JSON.parse(localStorage.getItem('studentJson'));
			$.each(read, function(index, value) {
				if (index >= firstItem && index < lastItem) {
					createList($('.table1'), index, value);
				}
			})
		}
	} else if ($(this).attr('id') == 'rightPage') {
		if ($('.pageNum[id=' + nowPage + ']').parent().next().children().eq(0).attr('id') != 'rightPage') {
			$(this).parent().removeClass('disabled');
			nowPage += 1;
			$("tr:not('.headline')").remove();
			firstItem = itemMax * (nowPage - 1);
			lastItem = itemMax * (nowPage);
			var read = JSON.parse(localStorage.getItem('studentJson'));
			$.each(read, function(index, value) {
				if (index >= firstItem && index < lastItem) {
					createList($('.table1'), index, value);
				}
			})
		}
	} else {

		$("tr:not('.headline')").remove();
		nowPage = parseInt($(this).attr('id'));
		firstItem = itemMax * (nowPage - 1);
		lastItem = itemMax * (nowPage);
		var read = JSON.parse(localStorage.getItem('studentJson'));
		$.each(read, function(index, value) {
			if (index >= firstItem && index < lastItem) {
				createList($('.table1'), index, value);
			}
		})
	}
});
//导出Excel
$(".export").on('click',function () {
    //列标题，逗号隔开，每一个逗号就是隔开一个单元格
    let str = `姓名,学号,班级,年级,性别,出生日期,家庭地址,家长姓名,联系电话,关系\n`;
    //增加\t为了不让表格显示科学计数法或者其他格式
    getExport=[];
    for(i=0;i<studentArr.length;i++){
        getoExport={
            name:studentArr[i].name,
            id:studentArr[i].id,
            class:studentArr[i].class,
            age:studentArr[i].age,
            sex:studentArr[i].sex,
            birth:studentArr[i].birth,
            address:studentArr[i].address,
            parent:studentArr[i].parent,
            phone:studentArr[i].phone,
            relation:studentArr[i].relation,
        }
        getExport.push(getoExport)
    }
    console.log(getExport)
    for(let i = 0 ; i < getExport.length ; i++ ){
        for(let name in getExport[i]){
            str+=`${getExport[i][name] + '\t'},`;     
        }
        str+='\n';
      }
      //encodeURIComponent解决中文乱码
      let uri = 'data:text/xls;charset=utf-8,\ufeff' + encodeURIComponent(str);
      //通过创建a标签实现
      var link = document.createElement("a");
      link.href = uri;
      //对下载的文件命名
      link.download =  "学生数据表.xls";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
});
//查询学生信息
$('.changeStudent').on('click',function () {
    let search=$('.search').val()
    $('tbody').html('');
    $('.pagination').html('')
    Pdd=true
            $.each(studentArr, function(index, value) {
                if (search==value.name||search==value.age||search==value.id) {
                    createList($('.table1'), index, value);
                    pd=false;
                    itemResort(1);
                    Pdd=false;
                }
                // return 0;
            });
    if (Pdd) {
        Pdd=false;
        $('tbody').append('<tr style="font-size: 30px"><td colspan="12">请正确输入查询信息</td></tr>')
    }
});
//清空查询后
$('.search').keyup(function (event) {
    if (event.keyCode==8) {
        $('tbody').html('')
        $.each(studentArr, function(index, value) {
            if (index >= firstItem && index < lastItem) {
                createList($('.table1'), index, value);
            }
        })
        createPage();
    }

})
$('.Add').on('click',function () {
    Jnm=studentArr[studentArr.length-1].id;
   var m=parseInt(Jnm)+1;
   $('#studio').val(m)
});
//添加学生
    $('#addQd').on('click',function () {
        let name=$('.addStudentInput').eq(0).val();
        let id=$('.addStudentInput').eq(1).val();
        let stuClass=$('.addStudentInput').eq(2).val();
        let age=$('.addStudentInput').eq(3).val();
        let stuSex=$('.addStudentInput').eq(4).val();
        let Year=$('.addStudentInput').eq(5).val();
        let Month=$('.addStudentInput').eq(6).val();
        let Day=$('.addStudentInput').eq(7).val();
        let address=$('.addStudentInput').eq(8).val();
        let parent=$('.addStudentInput').eq(9).val();
        let phone=$('.addStudentInput').eq(10).val();
        let relation=$('.addStudentInput').eq(11).val();
        Tn=$('tbody').children('tr').eq(0).children().eq(0).text()
        if ((phoneNumberReg.test(phone)) && (nameReg.test(parent))) {
            $('tbody').append('<tr><td></td><td>' + $('.addStudentInput').eq(0).val() + '</td><td>' + $('.addStudentInput').eq(1).val()  + 
            '</td><td>' + $('.addStudentInput').eq(2).val()  + 
            '</td><td>' +$('.addStudentInput').eq(3).val()  +'</td><td>' + $('.addStudentInput').eq(4).val()  + 
            '</td><td>' +$('.addStudentInput').eq(5).val()+'.'+$('.addStudentInput').eq(6).val()+'.'+$('.addStudentInput').eq(7).val() +'</td><td>' + $('.addStudentInput').eq(8).val()  + 
            '</td><td>' + $('.addStudentInput').eq(9).val()  +'</td><td>' + $('.addStudentInput').eq(10).val()  + 
            '</td><td>' + $('.addStudentInput').eq(11).val()  +'</td><td>' + 
            '<button type="button" class="btn btn-primary btn-sm edit" id="edit" data-toggle="modal" data-target="#studentEdit">编辑</button>' +
            '<button type="button" class="btn btn-warning btn-sm delete" id="delete" data-toggle="modal" data-target="#studentDelete">删除</button>' 
        );
        studentArr.push({
            num:'1',
            name:name,
            id:id,
            class:stuClass,
            age:age,
            sex:stuSex,
            birth:Year+'.'+Month+'.'+Day,
            address:address,
            parent:parent,
            phone:phone,
            relation:relation,
        })
        localStorage.setItem("studentJson" ,JSON.stringify(studentArr));//加入缓存
        if(pd){
        $('tbody').html('');
        $('.pagination').html('');
        createPage();
         nowPage=Math.ceil(Tn/6)
        firstItem = itemMax * (nowPage - 1);
        lastItem = itemMax * (nowPage)
        
        $.each(studentArr, function(index, value) {
            if (index >= firstItem && index < lastItem) {
                createList($('tbody'), index, value);
                itemResort(nowPage)
            }
        })
        $('.addStudentInput').eq(0).val('');
        $('.addStudentInput').eq(1).val('');
        $('.addStudentInput').eq(2).val();
        $('.addStudentInput').eq(3).val();
        $('.addStudentInput').eq(4).val();
        $('.addStudentInput').eq(5).val();
        $('.addStudentInput').eq(6).val();
        $('.addStudentInput').eq(7).val();
        $('.addStudentInput').eq(8).val('');
        $('.addStudentInput').eq(9).val('');
        $('.addStudentInput').eq(10).val('');
        $('.addStudentInput').eq(11).val('');
        $('#addStudentModal').modal('hide');
        innerHtml('');
        addJudge(false);
        }
        else{
            alert('添加未完成')
        }
    
        }
    })
//编辑学生信息
$('table').on('click','button[id=edit]',function () {
    oBtn=$(this).parent().parent();
    let name=$(oBtn).children().eq(1).text();
    let id=$(oBtn).children().eq(2).text();
    let studentClass=$(oBtn).children().eq(3).text();
    let age=$(oBtn).children().eq(4).text();

    let sex=$(oBtn).children().eq(5).text();

    let birth=$(oBtn).children().eq(6).text();
    //切割年月日
    let splice=birth.split('.');

    let address=$(oBtn).children().eq(7).text();

    let parent=$(oBtn).children().eq(8).text();

    let parentTel=$(oBtn).children().eq(9).text();

    let relation=$(oBtn).children().eq(10).text();

    $('#studentName').val(name)
    $('#Studio').val(id)
    $('#studentClass').val(studentClass)
    $('#studentAge').val(age)
    $('#studentSex').val(sex)
    $('#studentAddress').val(address)
    $('#parentName').val(parent)
    $('#parentTel').val(parentTel)
    $('#myRelation').val(relation)
    $('.sYear').val(splice[0])
    $('.sMonth').val(splice[1])
    $('.sDay').val(splice[2])
    console.log($('.sYear'),$('.sMonth'),$('.sDay'))
});
$('#viewQd').on('click',function () {
        let num=$('#StudentNum').val()
        let name=$('#studentName').val()
        let id=$('#Studio').val()
        let sClass=$('#studentClass').val()
        let age=$('#studentAge').val()
        let sex=$('#studentSex').val()
        let sYear=$('.sYear').val()
        let sMonth=$('.sMonth').val()
        let sDay=$('.sDay').val()
        let address=$('#studentAddress').val()
        let parent=$('#parentName').val()
        let phone=$('#parentTel').val()
        let relation= $('#myRelation').val()
        
        if ((phoneNumberReg.test(phone)) && (nameReg.test(parent))) {
            // console.log(num,name,id,studentClass,age,sex,address,parent,parentTel,relation)
            $(oBtn).children().eq(0).text(num);
            $(oBtn).children().eq(1).text(name);
            $(oBtn).children().eq(2).text(id);
            $(oBtn).children().eq(3).text(sClass);
            $(oBtn).children().eq(4).text(age);
            $(oBtn).children().eq(5).text(sex);
            $(oBtn).children().eq(6).text(sYear+'.'+sMonth+'.'+sDay);
            // $(oBtn).children().eq(6).html(sYear+'.'+sMonth+'.'+sDay);
            $(oBtn).children().eq(7).text(address);
            $(oBtn).children().eq(8).text(parent);
            $(oBtn).children().eq(9).text(phone);
            $(oBtn).children().eq(10).text(relation);
            console.log(sYear,sMonth,sDay)
            var k=$(oBtn).children().eq(0).text()-1
                    studentArr[k].name=name;
                    studentArr[k].id=id;
                    studentArr[k].class=sClass;
                    studentArr[k].age=age;
                    studentArr[k].sex=sex;
                    studentArr[k].birth=sYear+'.'+sMonth+'.'+sDay;
                    studentArr[k].address=address;
                    studentArr[k].parent=parent;
                    studentArr[k].phone=phone;
                    studentArr[k].relation=relation;
                
                localStorage.setItem("studentJson", JSON.stringify(studentArr));
            
            $('#studentEdit').modal('hide');
            itemResort(nowPage);
        }else{
            return ;
        } 
});
function getRegMsg(name) {
    var reg = '';
    switch (name) {
        case 'num':
            reg = studentStuAge;
            break;
        case 'name':
            reg = studentNameReg;
            break;
        case 'age':
            reg = studentStuAge;
            break;
        case 'address':
            reg = studentAddNamRel;
            break;
        case 'parent':
            reg = studentAddNamRel;
            break;
        case 'phone':
            reg = phoneNumberReg;
            break;
        case 'relation':
            reg = studentAddNamRel;
            break;
    }            
    return reg;
};
//指定将要删除哪行
$('table').on('click','button[id=delete]',function(){
    deleteItem=$(this).parent().parent();
});
//删除学生信息
$('#deletesResure').on('click',function () {
    Tn=$('tbody').children('tr').eq(0).children().eq(0).text()
    var m=($(deleteItem).children().eq(0).text())-1;
   k=$('tbody').children('tr').length;
    console.log(k)
    studentArr.splice(m,1);
    localStorage.setItem('studentJson',JSON.stringify(studentArr));
    $(deleteItem).remove();
    $('#studentDelete').modal('hide');
    nowPage=Math.ceil(Tn/6)
    if(pd){
        $('tbody').html('');
        $('.pagination').html('');
        createPage();
         
         console.log(nowPage)
         console.log(firstItem)
         console.log(lastItem)
        firstItem = itemMax * (nowPage - 1);
        lastItem = itemMax * (nowPage)
        $.each(studentArr, function(index, value) {
            if (index >= firstItem && index < lastItem) {
                createList($('tbody'), index, value);
                itemResort(nowPage)
            }
        })
        itemResort(nowPage);
    }
    if(k-1<=0 && nowPage>1){
        $('tbody').html('');
        $('.pagination').html('');
        createPage();
        firstItem = itemMax * (nowPage - 2);
        lastItem = itemMax * (nowPage-1);
        $.each(studentArr, function(index, value) {
            if (index >= firstItem && index < lastItem) {
                createList($('tbody'), index, value);
                itemResort(nowPage-1)
            }
        });
    } 
});